package com.lgCore.clientHandler;


import com.alibaba.fastjson.JSON;
import com.lgCore.common.ClientSession;
import com.lgCore.constants.ResultCode;
import com.lgCore.protoModel.ProtoMsg;
import com.lgCore.queue.ClientResultQueue;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 接受登录结果
 * 登录成功切换心跳处理
 * 记录session
 */
@Slf4j
@ChannelHandler.Sharable
@Service("LoginResponceHandler")
public class LoginResponceHandler extends ChannelInboundHandlerAdapter {

    /**
     * 业务逻辑处理
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        //判断消息实例
        if (null == msg || !(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }

        //判断类型
        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType headType = message.getLoginResponse().getType();
        if (!headType.equals(ProtoMsg.HeadType.LOGIN_RESPONSE)) {
            super.channelRead(ctx, msg);
            return;
        }
        ProtoMsg.LoginResponse loginResponse1 =  message.getLoginResponse();
        //登录返回并存放 客户唯一id
        Attribute<ClientSession> constantsAttributeKey = ctx.channel().attr(ClientSession.SESSION_KEY);
        if(loginResponse1.getResult() && ResultCode.SUCCESS.getCode().equals(loginResponse1.getCode())){
            //存放公共数据
            Channel channel = ctx.channel();
            ClientSession clientSession =  new ClientSession(channel);
            clientSession.setClientId(loginResponse1.getClientId());
            clientSession.setLogin(true);
            constantsAttributeKey.set(clientSession);

            //打开心跳事件，关闭登录事件
            channel.pipeline().addAfter("loginResponseHandler","heartBeatClientHandler",new HeartBeatClientHandler());
            channel.pipeline().remove("loginResponseHandler");



//            //发送请求
//            Date date = new Date();
//            for(int i=0;i<2;i++){
//
//                ProtoMsg.Message.Builder requestMessage = ProtoMsg.Message.newBuilder();
//                //登录请求
//                ProtoMsg.RpcRequest.Builder rpcRequest = ProtoMsg.RpcRequest.newBuilder();
//                rpcRequest.setRequestId(UUID.randomUUID().toString());
//                rpcRequest.setClientId(clientSession.getClientId());
//                rpcRequest.setServiceName("appService");
//                Object[] objects = new Object[2];
//                objects[0]="111111";
//                objects[1]="111111";
//                rpcRequest.setRequestObjects(JSON.toJSONString(objects));
//                rpcRequest.setType(ProtoMsg.HeadType.RPC_REQUEST);
//                requestMessage.setRpcRequest(rpcRequest);
//
//                //记录到队列
//                LinkedBlockingQueue<Object> responseQueue = new LinkedBlockingQueue<Object>(1);
//                ClientResultQueue.putResponse(clientSession.getClientId(), responseQueue);
//                channel.writeAndFlush(requestMessage);
//
//                //查询队列结果
//                Object result2 = responseQueue.poll(
//                        10L,
//                        TimeUnit.SECONDS);
//                System.out.println("拿到结果"+result2);
//            }
//            System.out.println("执行一百万次，运行时间："+(new Date().getTime()-date.getTime())+"毫秒");




        }
    }


}
